<?php

namespace App\Models\Traits;

use App\Models\AdminUsers;
use App\Util\LoginUtil;
use Illuminate\Database\Eloquent\Model;

trait HasCreatedByAdminIdAttribute
{
    protected static function bootHasCreatedByAdminIdAttribute()
    {
        static::creating(function (Model $model) {
            if (\Schema::hasColumn($model->getTable(), 'created_by_admin_id')) {
                $created_by_admin_id = LoginUtil::getAdminId();
                if ($created_by_admin_id) {
                    $model->setAttribute('created_by_admin_id', $created_by_admin_id);
                }
            }
        });
        static::saving(function (Model $model) {
            if (\Schema::hasColumn($model->getTable(), 'updated_by_admin_id')) {
                $updated_by_admin_id = LoginUtil::getAdminId();
                if ($updated_by_admin_id) {
                    $model->setAttribute('updated_by_admin_id', $updated_by_admin_id);//新增的时候 创建人和更新人一致才对
                }
            }
        });
    }

    public function createdAdmin()
    {
        return $this->belongsTo(AdminUsers::class, 'created_by_admin_id', 'id');
    }
}
